package com.tarena.lbs.user.service.impl;

import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.common.enums.Roles;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.user.dao.repository.AdminRepository;
import com.tarena.lbs.user.pojo.param.AdminParam;
import com.tarena.lbs.user.pojo.po.AdminPO;
import com.tarena.lbs.user.pojo.query.AdminQuery;
import com.tarena.lbs.user.pojo.vo.AdminVO;
import com.tarena.lbs.user.service.AdminService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AdminServiceImpl implements AdminService {
    @Resource
    private AdminRepository adminRepository;
    public AdminVO detail() {
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        AdminVO admin = new AdminVO();
        admin.setId(userPrinciple.getId());
        admin.setNickname(userPrinciple.getNickname());
        admin.setAccountType(userPrinciple.getRole().getType());
        return admin;
    }

    public PageResult<AdminVO> pageList(AdminQuery query) {
        List<AdminPO> adminVOS = adminRepository.selectList(query);
        List<AdminVO> adminVO = adminVOS.stream().map(this::convertToVO).collect(Collectors.toList());
        Long total = adminRepository.selectCount(query);
        PageResult<AdminVO> pageResult = new PageResult<>();
        pageResult.setTotal(total);
        pageResult.setObjects(adminVO);
        pageResult.setPageNo(query.getPageNo());
        pageResult.setPageSize(query.getPageSize());
        return pageResult;
    }

    private AdminVO convertToVO(AdminPO adminPO) {
        AdminVO vo = new AdminVO();
        BeanUtils.copyProperties(adminPO, vo);
        return vo;
    }

    public void save(AdminParam param) {
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        Roles role = userPrinciple.getRole();
        if (0 != role.getType()) {
            throw new RuntimeException("只有平台管理员可以添加账号");
        }
        AdminPO po = new AdminPO();
        BeanUtils.copyProperties(param, po);
        po.setCreateTime(new Date());
        adminRepository.save(po);
    }
}
